package com.qipay.utils;

import com.qipay.pay.entity.CpPayAlipayWapRequest;
import com.qipay.scalar.type.ApiStatusEnum;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

public class ResultUtils {

    public static Map<String, Object> createStatusResult(String status, String message) {

        Map<String, Object> result = new HashMap<>();
        if(StringUtils.isNotEmpty(status)) {
            result.put("status", status);
        }
        if(StringUtils.isNotEmpty(message)) {
            result.put("message", message);
        }

        return result;
    }

    public static Map<String, Object> wrapResult(Map<String, Object> result, CpPayAlipayWapRequest bean) {
        if(result.get("message")==null)
            result.put("message", ApiStatusEnum.getInfo((Integer) result.get("status")));
        result.put("out_trade_no", bean.getOutTradeNo());
        result.put("mch_id", bean.getMchId());
        result.put("total_fee", bean.getTotalFee());
        return result;
    }

    public static Map<String, Object> signResult(Map<String, Object> result,
                                                 String key, String signName, String keyName) {
        String sign = SignSortMD5Utils.getSign(result,
                key,signName,keyName);
        result.put("sign", sign);
        return result;
    }


    public static ApiStatusEnum getApiType(String errorMsg) {
        if(StringUtils.isBlank(errorMsg) || StringUtils.indexOf(errorMsg, ":") <= 0) {
            return ApiStatusEnum.SERVICE_ERR;
        }
        Integer code = Integer.valueOf(errorMsg.substring(0, errorMsg.indexOf(":")));
        if(code == null) {
            return ApiStatusEnum.SERVICE_ERR;
        }
        return ApiStatusEnum.getByType(code);
    }

    public static ApiStatusEnum getApiType(String errorMsg, ApiStatusEnum defaultStatus) {
        if(StringUtils.isBlank(errorMsg) || StringUtils.indexOf(errorMsg, "@@") <= 0) {
            return defaultStatus;
        }
        Integer code = Integer.valueOf(errorMsg.substring(0, errorMsg.indexOf("@@")));
        if(code == null) {
            return defaultStatus;
        }
        return ApiStatusEnum.getByType(code);
    }

    public static String getErrorMsg(String errorMsg) {
        if(StringUtils.isBlank(errorMsg)) {
            return ApiStatusEnum.SERVICE_ERR.getInfo();
        }

        if(StringUtils.indexOf(errorMsg, "@@") <= 0) {
            return errorMsg;
        }
        ApiStatusEnum apiStatusEnum = getApiType(errorMsg);
        return String.format("%s : %s", apiStatusEnum.getInfo()
                ,StringUtils.substring(errorMsg, errorMsg.indexOf(":") + 1));
    }

    public static String buildErrorMsg(ApiStatusEnum apiStatusEnum, String errorMsg) {
        return String.format("%d@@%s", apiStatusEnum.getCode(), errorMsg);
    }
}
